<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/3/3
 * Time: 下午6:14
 */

namespace App\HttpController;


use App\Bean\User;
use App\Model\User as Model;
use EasySwoole\Core\Http\AbstractInterface\Controller;
use EasySwoole\Core\Http\Message\Status;
use EasySwoole\Core\Swoole\ServerManager;


class Auth extends Controller
{

    //测试路径 /index.html
    public function index()
    {
        $this->actionNotFound('index');
    }

    /**
     * @param $action
     */
    protected function actionNotFound($action): void
    {
        $this->response()->withStatus(Status::CODE_NOT_FOUND);
        $this->response()->write("{$action} is not exist");
    }


    /**
     * token获取
     */
    public function auth() {
        // xisaoche,huiyao001x 测试数据

        $post = $this->request()->getParsedBody();
        $username = $post['user'];
        if (!$username) {
            $this->data_encode(null, 1001);
        }

        $password = $post['password'];
        if (!$password) {
            $this->data_encode(null, 1002);
        }

        $user = new User([
            'username'  => $username,
            'password'  => $password
        ]);
        $model = new Model();

        $user = $model->login($user);

        if (!$user) {
            $this->data_encode(null, 1003);
        }

        // 用户名加时间，多次登录会造成多个token出现
        // 用户名，会造成token永远不变，安全性不好
        $token = md5('user_' . $user->getUsername());
        $data = [
            'token' => $token
        ];
        $this->data_encode($data);

        // 记录，通过强制session_id写入
        // redis记录数据，需要经过封包和解包
        $this->session()->sessionId($token);
        $this->session()->sessionStart();
        $this->session()->set('userinfo', $user->toArray());
    }

    protected function data_encode($data, $code = 0, $message = '', $http_code = 200){
        $res_data = [
            'code'  => $code,
            'msg'   => $message
        ];
        if ($data) {
            $res_data['data'] = $data;
        }

        $this->response()->write(json_encode($res_data));
        $this->response()->end($http_code);
    }
}